package cookie;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * IllegalArgumentException: An invalid character [32] was present in the Cookie value
 * [32]代表空格，在cookie中的字符串不能有空格
 *
 * @author Mc.Chai
 * @program: JavaWeb
 * @create 2022-03-24-16:08 16:08
 */
@WebServlet("/CookieTest")
public class CookieTest extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        // 格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat();
        // a为am/pm的标记
        sdf.applyPattern("yyyy-MM-dd hh:mm:ss");
        // 获取当前时间
        Date date = new Date();
        PrintWriter writer = response.getWriter();
        //判断浏览器中是否有lastTime的cookie
        Cookie[] cookies = request.getCookies();
        boolean flag=false;
        if (cookies!=null){
            for (Cookie cookie : cookies) {

                if ("lastTime".equals(cookie.getName())){
                    //存在
                    String value = cookie.getValue();
                    String format = sdf.format(date);
                    //进行编码（解决日期中的空格字符）
                    String encode = URLEncoder.encode(format, "UTF-8");
                    //将新的访问日期进行赋值
                    cookie.setValue(encode);
                    //保存时间1个月
                    cookie.setMaxAge(60*60*24*30);
                    response.addCookie(cookie);
                    //进行解码
                    value = URLDecoder.decode(value, "utf-8");
                    writer.write("欢迎回来！你上次访问的时间为"+value);
                    flag=true;
                    break;
                }
            }

        }
        if (!flag){
            String format = sdf.format(date);
            String encode = URLEncoder.encode(format, "utf-8");
            Cookie lastTime = new Cookie("lastTime", encode);
            //保存时间1个月
            lastTime.setMaxAge(60*60*24*30);
            response.addCookie(lastTime);


            writer.write("你好！欢迎首次访问");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }
}
